function initLhp() {
  var lhpConfObj = {
        id: 'leftHandPanelsContainer',
        panelNames : ['panel1', 'panel2',  'panel3']
}

  lhpsObj = new LeftHandPanels(lhpConfObj);

}

function initFooter() {
  var footerConfObj = {
        id: 'randomfootercontainer',
        tabs: [{
                        color:'blue',
                        clickPanelSelector:'.leftHandPanel:nth-child(1)',
                        text:'Leaderboard'
                  },
                {
                                color:'red',
        clickPanelSelector:'.leftHandPanel:nth-child(2)',
                                text:'Campaign'
                          },
                        {
                                        color:'green',
          clickPanelSelector:'.leftHandPanel:nth-child(3)',
                                        text:'StrongHold'
                                  },
                        {
                                        color:'#666',
                                  //clickPanelSelector:'.leftHandPanel:nth-child(4)',
                                        text:'Scoreboard'
                                  }
                        ]
}

  footer = new Footer(footerConfObj);

}

function Category(name, counter){
	this.name = name;
	this.counter = counter;
	var thisInstance = this;
   this.state = "unpressed";
	this.press = function(){
		if(this.state=="pressed") return;
		var name = this.name;
		var ele = document.querySelector("div[categoryname="+name+"]");
		this.onclick.call(ele);
	};
	this.unpress = function(){
   console.log(this.state);
			if(this.state=="unpressed") return;
			var name = this.name;
         console.log(this.name);
			var ele = document.querySelector("div[categoryname="+name+"]");
         console.log(ele);
			this.onclick.call(ele);
	};
	this.increaseCounter = function(){
		var that = this;
		var thisDiv = document.querySelector('div[categoryname='+that.name+']');
		var addDiv = thisDiv.querySelector("div[name=addDiv]");
		that.fadeUpside(addDiv);
		var counterDiv = thisDiv.querySelector("div[name=counter]");
		counterDiv.className = 'rotateClock';
	};
	this.decreaseCounter = function(){
		var that = this;
		var thisDiv = document.querySelector('div[categoryname='+that.name+']');
		var addDiv = thisDiv.querySelector("div[name=removeDiv]");
		that.fadeUpside(addDiv);
		var counterDiv = thisDiv.querySelector("div[name=counter]");
		counterDiv.className = 'rotateAntiClock';
	};
	this.markerClicked = function(){
		//call this when you click on pin inside a category button [to add a marker on map]
		console.log('marker clicked', this, thisInstance);
      //click on marker
      if (this.name == "Restaurants") {
			    markerUrl = RES_USER_ICON;
          bufferGlobal.campaignId = "Restaurants";   
			}
			else if (this.name == "Cafes") {
			    markerUrl = CAFE_USER_ICON;
          bufferGlobal.campaignId = "Cafes";  
			}
			else if (this.name == "Hospitals") {
			    markerUrl = HOS_USER_ICON;
          bufferGlobal.campaignId = "Hospitals";   
			}
      addMarkerOn();
      
	};
	this.onclick = function(e){
     if(e){
		var targetname = e.target.getAttribute("name");
		if(targetname=="markerimage" || targetname=="markercontainer"){
			thisInstance.markerClicked();
			return;
		}
   }
		var classname = "unpressed";
		if(this.className.indexOf(classname)>-1){
			this.className = "pressed";
        if (bufferGlobal.marker) {
          bufferGlobal.marker.setMap(null);
          bufferGlobal.marker = null;
        }
			if (this.getAttribute("categoryname") == "Restaurants") {
          map.overlayMapTypes.clear();
          map.overlayMapTypes.insertAt(
							 0, new CategoryMapType(new google.maps.Size(256, 256)));

			    categoryString = RES_STRING;
			    imgUrl = RES_ICON;
			    obj.categories['Cafes'].unpress();
			    obj.categories['Hospitals'].unpress();
			    bufferGlobal.pressed = true;
			}
			else if (this.getAttribute("categoryname") == "Cafes") {
			    map.overlayMapTypes.clear();
          map.overlayMapTypes.insertAt(
							 0, new CategoryMapType(new google.maps.Size(256, 256)));

			    categoryString = CAFE_STRING;
			    imgUrl = CAFE_ICON;
			    obj.categories['Restaurants'].unpress();
			    obj.categories['Hospitals'].unpress();
			    bufferGlobal.pressed = true; 
			}
			else if (this.getAttribute("categoryname") == "Hospitals") {
          map.overlayMapTypes.clear();
          map.overlayMapTypes.insertAt(
							 0, new CategoryMapType(new google.maps.Size(256, 256)));

			    categoryString = HOS_STRING;
			    imgUrl = HOS_ICON;
			    obj.categories['Cafes'].unpress();
			    obj.categories['Restaurants'].unpress();
			    bufferGlobal.pressed = true;
   }
         //on press 
         //get name using this.name
    thisInstance.state = "pressed";
		}else{
      
      if (bufferGlobal.marker) {
          bufferGlobal.marker.setMap(null);
          bufferGlobal.marker = null;
        }
      
		    if (this.getAttribute("categoryname") == "Restaurants") {
			bufferGlobal.pressed = false;
			map.overlayMapTypes.clear();
        }
		    else if (this.getAttribute("categoryname") == "Cafes") {
			bufferGlobal.pressed = false;
			map.overlayMapTypes.clear();
        }
		    else if (this.getAttribute("categoryname") == "Hospitals") {
			bufferGlobal.pressed = false;
			map.overlayMapTypes.clear();
        }
		    deleteOverlaysFetched();
		    this.className=classname;
		    
         //on unpress
         //get  name using this.name
          thisInstance.state = "unpressed";
		}
      
    
		/*
		var detailEle = this.nextSibling;
		while(detailEle.getAttribute("name")!="categorydetails"){
			detailEle = detailEle.nextSibling;
		}
		
		var classname = detailEle.className;
		if(detailEle.getAttribute("state")=="closed"){
			//need to open
			detailEle.style.height="100px";
			detailEle.setAttribute("state","opened");
		}else{
			//need to close
			detailEle.style.height="0px";
			detailEle.setAttribute("state","closed");
		}*/
		
      
      //click on category
	};
	
	this.fillContent = function(content){
		this.content = content;
		var detailEle = document.querySelector("div[categoryname="+this.name+"]").nextSibling;
		while(detailEle.getAttribute("name")!="categorydetails"){
			detailEle = detailEle.nextSibling;
		}
		detailEle.firstChild.innerHTML  = content;
	};
	
	this.fadeUpside = function(element){
		addButton = element;
		addButton.style.display = "block";
		addButton.style.opacity = 1;
		addButton.style.top = '-10px';
		var initialTop = addButton.style.top;
		var initialOpacity = addButton.style.opacity;
		var intervalFunc = window.setInterval(function(){
			var top = parseInt(addButton.style.top,10);
			var opacity = parseFloat(addButton.style.opacity,10);
			top = top - 5;
			opacity = opacity - 0.05;
			addButton.style.top = top+"px";
			addButton.style.opacity = opacity;
			if(opacity<=0){
					window.clearInterval(intervalFunc);
					addAnimationOn = false;
					addButton.style.top = initialTop;
					addButton.style.opcacity = 1;
					addButton.style.display = "none";
			}
		}, 20);
	}
};

function ManageMarkers(){
	this.categories = {};
	this.init = function(){
		this.parent = document.getElementsByName("componentContainer")[0];
		
		this.render();
		this.component = this.parent.firstChild;
		this.collapseButton = document.getElementById("collapseButton");
		this.expandButton = document.getElementById("expandButton");
		this.updateEvents();
		//	this.addCategory("Cafes",0);
		//this.addCategory("Hospitals",0);
		//this.addCategory("Restaurant",0);
	}
	
	this.addCategory = function(name, counter){
		if(this.categories[name]){
			alert('category already exists');
			return;
		}
		this.categories[name] = new Category(name, counter);
		this.render();
		this.updateEvents();
	};
	
	this.removeCategory = function(name){
		this.categories[name] = undefined;
		delete this.categories[name];
		this.render();
		this.updateEvents();
	};
	
	this.render = function(){
		var html = [];
		html.push('<div style="position:relative;height:100%;margin-right:10px;">');
		html.push('<div id="collapseButton" style="position:absolute;cursor:pointer;"></div>');
		html.push('<div id="expandButton" style="position:absolute;left:-3px;top:0px;cursor:pointer;display:none;">');
		
		for(categoryname in this.categories){
			html.push('<div name="category"><img src="http://gmapgame.googlecode.com/svn/trunk/markerPlace.png"/></div>')
		}
		html.push('</div>');
		
		html.push('<div name="categorycontainer" style="position: relative; left: 12px; top: 0px;padding-bottom:10px;">');
		html.push('</div>');
		html.push('</div>');
		this.parent.innerHTML = html.join("");
		html = [];
		
		//render all categories
    var countB = 1;  
		for(categoryname in this.categories){
			var category = this.categories[categoryname];
			html.push('<div categoryname="'+category.name+'" class="unpressed" name="category">'+category.name);
			html.push('<div name="markercontainer" class="markerContainer"><img name="markerimage" src="http://gmapgame.googlecode.com/svn/trunk/marker' + countB + '.png"style="width: 13px;"></div>');
				html.push('<div name="addDiv">');
					html.push('<img height="33" src="http://gmapgame.googlecode.com/svn/trunk/add.png">');
				html.push('</div>');
				html.push('<div name="removeDiv">');
					html.push('<img height="33" src="http://gmapgame.googlecode.com/svn/trunk/remove.png">');
				html.push('</div>');
				html.push('<div name="counter">'+category.counter+'</div>');
			html.push('</div>');
			html.push('<div name="categorydetails" style="height:0px;" state="closed"><div>');
			category.content = category.content ? category.content : "Expandable and collapsable content";
			html.push(category.content);
			html.push('</div></div>');
			countB++;
			
		}
		document.getElementsByName("categorycontainer")[0].innerHTML = html.join("");
		this.component = this.parent.firstChild;
		this.collapseButton = document.getElementById("collapseButton");
		this.expandButton = document.getElementById("expandButton");
		
	
	};
	
	this.updateEvents = function(){
		var that = this;
		var counters = document.querySelectorAll("div[name=counter]");
		for(var i=0; i<counters.length; i++){
			var counter = counters[i];
			counter.addEventListener('webkitAnimationEnd', function(){
				var ele = this;
				var value = parseInt(ele.innerHTML, 10);
				var className = ele.className;
				ele.className="";
				if(typeof value=='number' && className=='rotateClock'){
					ele.innerHTML = ++value;
				}else{
					ele.innerHTML = --value;
				}
			});
		}
		
		for(categoryname in this.categories){
			var category = document.querySelector('div[categoryname='+categoryname+']');
			category.onclick = this.categories[categoryname].onclick;
		}
		
		this.collapseButton.onclick = function(){ 
			that.collapse()
		};
		this.expandButton.onclick = function(){ 
			that.expand()
		};
		
		this.parent.addEventListener('webkitAnimationEnd', function(){
				var currentClass = this.className;
				
				if(currentClass.indexOf("componentCollapse")>=0){
					//that.collapseButton.style.display = "none";
					//that.expandButton.style.display = "block";
					that.parent.style.width = "40px";
				}else if(currentClass.indexOf("componentExpand")>=0){
					//that.collapseButton.style.display = "block";
					//that.expandButton.style.display = "none";
					that.parent.style.width = "228px";
				}
				currentClass = currentClass.replace("componentCollapse","");
				currentClass = currentClass.replace("componentExpand","");
				this.className = currentClass;
		});
		
		
		
		
	};
	
	this.collapse = function(){
		this.parent.className = "componentCollapse";
      
    var tabElement = document.getElementsByName("widgetFooter")[0].lastChild;
		tabElement.setAttribute("pressed",false); 
		while(tabElement.className.indexOf("footertabselected")>0){
			tabElement.className = tabElement.className.replace("footertabselected","");
		}
	};
	
	this.expand = function(){
		this.expandButton.style.display = "none";
		this.parent.className = "componentExpand";
      var tabElement = document.getElementsByName("widgetFooter")[0].lastChild;
			tabElement.setAttribute("pressed",true); 
			tabElement.className += " footertabselected";
	}
	
	
	this.init();
	this.collapse();
};


var InfoWindow = function(x,y){
	this.pos = [100, 100];
	if(x && y){this.pos[0] = x; this.pos[1] = y};
	this.render = function(){
		var html = [];
		var id = "infoWindow"+parseInt(Math.random()*1000,10);
		this.id = id;
		html.push('<div style="display:none;" id="'+id+'" name="component">');
		html.push('<div class="closeButton">+</div>');
		html.push('<div name="content">');
		html.push('</div>');
		html.push('<div name="tip">');
		html.push('</div>');
		html.push('</div>');
		var testContainer = document.createElement("div");
		testContainer.innerHTML = html.join("");
		document.body.appendChild(testContainer.firstChild);
		this.component = document.getElementById(id);
		this.closeButton = this.component.querySelector("div.closeButton");
		this.component.style.left = this.pos[0]+"px";
		this.component.style.top = this.pos[1]+"px";
		this.show();
		
		this.updateEvents();
	};
	
	this.hide = function(){
		this.component.style.display = "none";
	};
	
	this.show = function(){
		this.component.style.display = "block";
	};
	
	this.updateEvents = function(){
		var me = this;
		this.closeButton.onclick = function(){
			me.hide();
		}
	};
	//this method expects string HTML
	this.fillContent = function(html){
		var component = this.component;
		var contentHolder = component.firstChild;
		
		while(contentHolder.getAttribute("name")!="content"){
			contentHolder = contentHolder.nextSibling;
		}
		var contentPadder = document.createElement("div");
		contentPadder.style.padding = "15px";
		contentPadder.innerHTML = html;
		contentHolder.innerHTML = "";
		contentHolder.appendChild(contentPadder);
		
	}
	
	this.repositionAt = function(x, y){
		this.tipPosition = [x, y];
	};
	
	this.render();
}


var Footer = function(confObj){
	this.parentElementId = confObj.id;
	this.parentElement = document.getElementById(this.parentElementId);
	this.tabs = confObj.tabs;
	this.render = function(){
		/*
		<div name="widgetFooter">
			<div name="footertab" name="firstchild">Campaign</div>
			<div name="footertab">Leaderboard</div>
			<div name="footertab">asda</div>
			<div name="footertab" name="lastchild">asda</div>
		</div>
		*/
		var html = [];
		html.push('<div name="widgetFooter">');
		var tabs = this.tabs;
			for(var i=0; i<tabs.length; i++){
				html.push('<div pressed="false" tabnum="'+i+'" style="background-color:'+tabs[i].color+';" class="footertab">'+tabs[i].text+'</div>')
			}
		html.push('</div>');
		this.parentElement.innerHTML = html.join("");
		this.updateEvents();
	}
	
	this.updateEvents = function(){
		var me = this;
		var tabs = this.parentElement.getElementsByClassName("footertab");
		for(var i=0, length=tabs.length; i<length; i++){
			tabs[i].onclick = function(e){
				me.tabOnClick(e, this);
			}
		}
	}
	
	this.tabOnClick = function(e, thisElement){
		var tabNum = parseInt(thisElement.getAttribute("tabnum"),10);
		var pressed = thisElement.getAttribute("pressed");
		if(pressed=="true"){
			if(this.tabs[tabNum].clickPanelSelector){
				lhpsObj.collapsePanel(this.tabs[tabNum].clickPanelSelector);
			}
			thisElement.className = thisElement.className.replace("footertabselected","");
			if(tabNum==this.tabs.length-1){
				obj.collapse();
			}
			thisElement.setAttribute("pressed","false");
		}else{
				var alreadySelectedTabs = this.parentElement.getElementsByClassName("footertabselected");
				for (var i=0, length=alreadySelectedTabs.length; i<length; i++){
					var className = alreadySelectedTabs[i].className;
					className = className.replace("footertabselected","");
					alreadySelectedTabs[i].setAttribute("pressed","false");
					alreadySelectedTabs[i].className = className;
				}
				thisElement.className += " footertabselected";
				if(this.tabs[tabNum].clickPanelSelector){
					lhpsObj.expandPanel(this.tabs[tabNum].clickPanelSelector, true)
				}

				if(tabNum==this.tabs.length-1){
					obj.expand();
				}
				thisElement.setAttribute("pressed","true");
		}
	
		
		
	}
	this.render();
}

var LeftHandPanels = function(confObj){
	/*
	{
	id : 'parentId',
	panelNames : ['panel1', 'panel2',  'panel3'];
	}
	*/
	this.parentId = confObj.id;
	this.parent = document.getElementById(this.parentId);
	this.panelNames = confObj.panelNames;
	
	this.render = function(){
		var html = [];
		var panels = this.panelNames;
		for(var i=0, length=this.panelNames.length; i<length; i++){
			html.push('<div class="leftHandPanel" name="'+panels[i]+'">');
			var alreadyCreatedPanel = document.querySelector("div#"+this.parentId+" div[name="+panels[i]+"]");
			if(alreadyCreatedPanel){
				html.push(alreadyCreatedPanel.innerHTML);
			}else{
				html.push(panels[i]);
			}
			html.push('</div>');
		}
		this.parent.innerHTML = html.join("");
		this.updateEvents();
		document.querySelectorAll(".leftHandPanel")[1].className += " collapseToLeft";
	}
	
	this.updateEvents = function(){
		//Write here in case you want to attach some event handlers after rendering
		var panels = document.querySelectorAll("div#"+this.parentId+" div[class=leftHandPanel]");
		for(var i=0, length=panels.length; i<length; i++){
			panels[i].addEventListener('webkitAnimationEnd', function(){
				var ele = this;
				var className = ele.className;
				if(className.indexOf('expandToRight')>=0){
					ele.style.width = "409px";
				}else{
					ele.style.width = "0px";
				}
				className = className.replace("expandToRight","");
				className = className.replace("collapseToLeft","");
				ele.className=className;
			});
		}
	};
	
	this.collapsePanel = function(selector){
		document.querySelector("div#"+this.parentId+" "+selector).className += " collapseToLeft";
	};
	
	this.expandPanel = function(selector, collapseOthers){
		if(collapseOthers){
			var panels = document.querySelectorAll("div#"+this.parentId+" .leftHandPanel");
			for(var i=0, length=panels.length; i<length; i++){
				if(parseInt(panels[i].style.width,10)>0){
					console.log('open found',i);
					panels[i].className+=" collapseToLeft";
				}
			}
			//Logic to collapse already expanded panels
		}
		document.querySelector("div#"+this.parentId+" "+selector).className += " expandToRight";
	}
	this.render();
}
